﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

[assembly:WebResource("LO1200.Web.UI.Scripts.TwitterFeed.js", "text/javascript")]

namespace LO1200.Web.UI
{
    [ToolboxData("<{0}:TwitterFeed runat=server></{0}:TwitterFeed>")]
    public class TwitterFeed : WebControl
    {
        /// <summary>
        /// Gets or sets the text to search Twitter for.
        /// </summary>
        [Bindable(true)]
        [Category("Data")]
        [Description("The text to search Twitter for.")]
        [DefaultValue("")]
        public string SearchQuery
        {
            get
            {
                var result = ViewState["FeedUrl"];
                if (result == null) return string.Empty;
                return (string)result;
            }
            set { ViewState["FeedUrl"] = value; }
        }
        /// <summary>
        /// Gets or sets the maximum amount of items to display.
        /// </summary>
        [Bindable(true)]
        [Category("Appearance")]
        [Description("The maximum amount of items to display.")]
        [DefaultValue(10)]
        public int MaxItems
        {
            get
            {
                var result = ViewState["MaxItems"];
                if (result == null) return 10;
                return (int)result;
            }
            set { ViewState["MaxItems"] = value; }
        }
        /// <summary>
        /// Gets or sets the format to display the date in.
        /// </summary>
        [Bindable(true)]
        [Category("Data")]
        [Description("The format to display the date in.")]
        [DefaultValue("")]
        public string DateFormat
        {
            get
            {
                var result = ViewState["DateFormat"];
                if (result == null) return string.Empty;
                return (string)result;
            }
            set { ViewState["DateFormat"] = value; }
        }
        /// <summary>
        /// Gets or sets the language to search for.
        /// </summary>
        [Bindable(true)]
        [Category("Data")]
        [Description("The language to search for.")]
        [DefaultValue(TwitterLanguage.Any)]
        public TwitterLanguage Language
        {
            get
            {
                var result = ViewState["Language"];
                if (result == null) return TwitterLanguage.Any;
                return (TwitterLanguage)result;
            }
            set { ViewState["Language"] = value; }
        }
        /// <summary>
        /// Gets or sets the interval at which to poll Twitter.
        /// </summary>
        [Bindable(true)]
        [Category("Behavior")]
        [Description("The interval at which to poll Twitter.")]
        [DefaultValue(1000)]
        public int Interval
        {
            get
            {
                var result = ViewState["Interval"];
                if (result == null) return 1000;
                return (int)result;
            }
            set { ViewState["Interval"] = value; }
        }

        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.PreRender"/> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs"/> object that contains the event data. </param>
        protected override void OnPreRender(EventArgs e)
        {
            Common.RegisterScripts(Page);
            Page.ClientScript.RegisterClientScriptResource(typeof (TwitterFeed), "LO1200.Web.UI.Scripts.TwitterFeed.js");
            base.OnPreRender(e);
        }

        /// <summary>
        /// Renders the contents of the control to the specified writer. This method is used primarily by control developers.
        /// </summary>
        /// <param name="writer">A <see cref="T:System.Web.UI.HtmlTextWriter"/> that represents the output stream to render HTML content on the client. </param>
        protected override void RenderContents(HtmlTextWriter writer)
        {
            writer.AddAttribute(HtmlTextWriterAttribute.Class, "TweetContainer");
            writer.RenderBeginTag(HtmlTextWriterTag.Ul);

            foreach (var tweet in TwitterFeedHandler.GetTweets(SearchQuery, Language, MaxItems, 0))
            {
                writer.AddAttribute(HtmlTextWriterAttribute.Class, "Tweet");
                writer.RenderBeginTag(HtmlTextWriterTag.Li);
                {
                    writer.AddAttribute(HtmlTextWriterAttribute.Class, "Content");
                    writer.RenderBeginTag(HtmlTextWriterTag.P);
                    {
                        writer.AddAttribute(HtmlTextWriterAttribute.Class, "Author");
                        writer.AddAttribute(HtmlTextWriterAttribute.Href, string.Format("http://www.twitter.com/{0}", tweet.AuthorUsername));
                        writer.RenderBeginTag(HtmlTextWriterTag.A);
                        writer.Write(tweet.AuthorUsername);
                        writer.Write(": ");
                        writer.RenderEndTag();
                        writer.Write(HttpUtility.HtmlDecode(tweet.Content));
                    }
                    writer.RenderEndTag();

                    writer.AddAttribute(HtmlTextWriterAttribute.Class, "Date");
                    writer.RenderBeginTag(HtmlTextWriterTag.H3);
                    if (!string.IsNullOrWhiteSpace(DateFormat)) writer.Write(tweet.Date.ToString(DateFormat));
                    else writer.Write(tweet.Date);
                    writer.RenderEndTag();
                }
                writer.RenderEndTag();
            }

            writer.RenderEndTag();
        }

        /// <summary>
        /// Renders the HTML closing tag of the control into the specified writer. This method is used primarily by control developers.
        /// </summary>
        /// <param name="writer">A <see cref="T:System.Web.UI.HtmlTextWriter"/> that represents the output stream to render HTML content on the client. </param>
        public override void RenderEndTag(HtmlTextWriter writer)
        {
            base.RenderEndTag(writer);

            if (DesignMode) return;

            writer.AddAttribute(HtmlTextWriterAttribute.Type, "text/javascript");
            writer.RenderBeginTag(HtmlTextWriterTag.Script);
            writer.WriteLine("$create({0}, {{ query:'{1}', maxTweets:{2}, interval:{3} }}, null, null, $get('{4}'));", "LO1200.Web.UI.TwitterFeed", HttpUtility.JavaScriptStringEncode(SearchQuery), MaxItems, Interval, ClientID);
            writer.RenderEndTag();
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="T:LO1200.Web.UI.TwitterFeed"/> class.
        /// </summary>
        public TwitterFeed()
            : base(HtmlTextWriterTag.Div)
        {
        }
    }
}
